package com.lw.leetcode.other.b;

/**
 * Created with IntelliJ IDEA.
 * 43. 字符串相乘
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/20 13:26
 */
public class Multiply {
    public String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }
        int l1 = num1.length();
        int l2 = num2.length();
        int l3 = l1 + l2;
        int[] a = new int[l1];
        int[] b = new int[l2];
        int n = l1;
        byte[] b1 = num1.getBytes();
        for (byte by : b1) {
            a[--n] = by - 48;
        }
        n = l2;
        byte[] b2 = num2.getBytes();
        for (byte by : b2) {
            b[--n] = by - 48;
        }
        int[][] arr = new int[l2][l3];
        for (int i = 0; i < l2; i++) {
            for (int j = 0; j < l1; j++) {
                int sum = a[j] * b[i];
                arr[i][j + i] = arr[i][j + i] + sum;
            }
        }
        int[] cc = new int[l3];
        for (int i = 0; i < l3; i++) {
            for (int j = 0; j < l2; j++) {
                cc[i] = cc[i] + arr[j][i];
            }
            if (cc[i] > 9) {
                int s = cc[i] / 10;
                int x = cc[i] % 10;
                cc[i] = x;
                cc[i + 1] = s;
            }
        }

        StringBuilder sb = new StringBuilder();
        boolean flag = false;
        for (int i = l3 - 1; i >= 0; i--) {
            if (flag || cc[i] != 0) {
                sb.append(cc[i]);
                flag = true;
            }
        }
        return sb.toString();
    }
}
